// app.js
import http from './utils/http'
import { randomStr } from './utils/util'
import {EventEmitter} from './utils/EventEmitter'
wx.$http = http
wx.$theme = {
  color: '#ff9614'
}

wx.$eventEmitter = EventEmitter;

App({
  onLaunch() {
    // 展示本地存储能力
    wx.setStorageSync('uuid', randomStr(16))
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    this.addFormat()
  },
  onShow() {
   console.log('======app onshow')
   wx.$wechatLogin = { 
      state: "pending",
      promise : this.wechatLogin()
    };
  },
  onHide () {
    try {
      const res = wx.getStorageInfoSync()
      const linkKeys = res.keys.filter(k => /^link_pwd/.test(k));
      linkKeys.forEach(k => wx.removeStorageSync(k));
    } catch (e) {
      // Do something when catch error
    }
  },
  globalData: {
    userInfo: null
  },

  addFormat() {
		Date.prototype.Format = function(fmt='yyyy-MM-dd HH:mm'){
			const o = {
        "y+": this.getFullYear(),
        "M+": this.getMonth()+1,
        "d+": this.getDate(),
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
				"S+": this.getMilliseconds()
			};
			let res = fmt;
			Object.keys(o).forEach(i => {
					const reg = new RegExp(i);
					if (reg.test(res)) {
							res = res.replace(reg, o[i] < 0x0A ? ("0" + o[i]) : ("" + o[i]))
					}
			});
			return res;
		}
   },

   wechatLogin() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          wx.$http.get({url: "/wechatLogin/getMiniProgramOpenid", data: {code: res.code}, noToken: true})
              .then(res => {
                  const {id, openid, unionid, tokenMap} = res.data;
                  const userInfo = wx.getStorageSync('wechatInfo') || {};
                  userInfo.wechatId = id;
                  userInfo.openid = openid;
                  userInfo.unionid = unionid;
                  wx.setStorageSync('wechatInfo', userInfo)
                  if (tokenMap) {
                    wx.setStorageSync('szm_token', tokenMap)
                  }
                  resolve(res.data)
              })
              .catch(() => reject())
              .finally(() => {
                wx.$wechatLogin.state = "fulfilled"
              });
        },
        fail: (err)=> {
          console.error(err);
          reject();
        }
      })
    });
  },
})
